// <editor-fold defaultstate="collapsed" desc="GNU GPLv3 Header">
/*
 * File:   ChunkDataPCMByte.c
 *
 * Copyright (C) 2013 Robert Antoni Buj Gelonch <rbuj@uoc.edu>
 * Copyright (C) 2013 David Megias Jimenez <dmegias@uoc.edu>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
// </editor-fold>

#include "../ChunkDataPCMByte.h"

/**
 *
 * @param file
 * @param channels
 * @return
 */
ChunkDataPCMByte* readChunkDataPCMByte(FILE* file, int channels) {
    int i, j, lenght;
    ChunkDataPCMByte* chunkDataPCMByte = malloc(sizeof (ChunkDataPCMByte));
    chunkDataPCMByte->chunkDataPCM = readChunkDataPCM(file);
    lenght = (chunkDataPCMByte->chunkDataPCM->data->ck->size) / channels;
    chunkDataPCMByte->samples = malloc(channels * lenght * sizeof (short int));
    for (i = 0; i < lenght; i++) {
        for (j = 0; j < channels; j++) {
            readByteLE(file, &chunkDataPCMByte->samples[(lenght * j) + i]);
        }
    }
    return chunkDataPCMByte;
}

/**
 *
 * @param chunkDataPCMByte
 */
void freeChunkDataPCMByte(ChunkDataPCMByte* chunkDataPCMByte) {
    freeChunkDataPCM(chunkDataPCMByte->chunkDataPCM);
    free(chunkDataPCMByte->samples);
    free(chunkDataPCMByte);
}

/**
 *
 * @param chunkDataPCMByte
 * @param channels
 * @param file
 */
void writeChunkDataPCMByte(ChunkDataPCMByte* chunkDataPCMByte, int channels,
        FILE* file) {
    int i, j, lenght;
    writeChunkDataPCM(chunkDataPCMByte->chunkDataPCM, file);
    lenght = (chunkDataPCMByte->chunkDataPCM->data->ck->size) / channels;
    for (i = 0; i < lenght; i++) {
        for (j = 0; j < channels; j++) {
            writeByteLE(&chunkDataPCMByte->samples[(lenght * j) + i], file);
        }
    }
}
